package com.wfl.sampling.aop;

import com.alibaba.fastjson.JSONObject;
import com.wfl.sampling.dao.OperateLogDao;
import com.wfl.sampling.entity.OperateLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
public class LogAspect {
    @Autowired
    private OperateLogDao operateLogDao;
//    @Autowired
//    private HttpServletRequest request;

    @Around("@annotation(com.wfl.sampling.anno.Log)")
    public Object recordLog(ProceedingJoinPoint pjp) throws Throwable {
        //操作人的ID-当前登录员工ID，通过jwt令牌直接获取，由于是AOP编程
//        String jwt = request.getHeader("token");
//        Claims claims = JwtUtils.parseJwt(jwt);
        Integer operateUser = null;
//        operateUser = (Integer)claims.get("id");
        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        //操作类名
        String className = pjp.getTarget().getClass().getName();

        //操作方法
        String methodName = pjp.getSignature().getName();

        //方法参数
        Object[] args = pjp.getArgs();
        String methodParams = Arrays.toString(args);

        //操作耗时
        Long begin = System.currentTimeMillis();
        //调用原始目标方法
        Object result = pjp.proceed();
        String returnValues = JSONObject.toJSONString(result);
        if(returnValues.length()>10000)
            result="数据太长了存不进去";
        Long end = System.currentTimeMillis();
        OperateLog operateLog = new OperateLog(null, operateUser,className,methodParams,methodName,returnValues,end-begin);
        operateLogDao.insertLog(operateLog);
        return result;
    }
}
